if (typeof window.console != 'object') {
    window.console = { log: function () { } };
}
//#################################################
var BASE_URL = "";
var chunkSize = 10 * 1024 * 1024; //分块大小
var userInfo = {
    userId: "the_user",         // 秘钥
    md5: "",
    category: "",
    uniqueFileName: ""
}; //用户会话信息

var _cache = {};
//#################################################
var uniqueFileName = null; //文件唯一标识符
var md5Mark = null;
var uploader;
jQuery(function () {
    //#############################################
    WebUploader.Uploader.register({
        "before-send-file": "beforeSendFile",
        "before-send": "beforeSend",
        "after-send-file": "afterSendFile"
    },
        {
            beforeSendFile: function (file) {
				var tempFileType = file.source.type.toLowerCase();
				if (tempFileType.indexOf('mp4') < 0 && tempFileType.indexOf('webm') < 0 || testTemp == 1) {
					return;
				}else {
					var task = new $.Deferred();
					(new WebUploader.Uploader()).md5File(file, 0, 200 * 1024 * 1024).progress(function (percentage) {
					}).then(function (val) {
					    md5Mark = val;
					    userInfo.md5 = val;
					    $.ajax({
					        type: "GET",
					        url: ServerUrl,
					        data: {
					            status: "md5Check",
					            md5: val,
					            uploadkey: userInfo.userId,
					            name: file.name.replace("." + file.ext, "")
					        },
					        cache: false,
					        timeout: 3000,
					        //todo 超时的话，只能认为该文件不曾上传过
					        dataType: "json"
					    }).then(function (data, textStatus, jqXHR) {
					        if (data.err_code) {
					            if (data.err_code == 1)
					                task.reject("上传密钥错误!");
					            else
					                task.reject("未经许可的上传域名!");
					            return;
					        }
					        // alert(JSON.stringify(data));
					        if (data.ifExist) { 
					            //若存在，这返回失败给WebUploader，表明该文件不需要上传
					            if (data.share) {
									// 储存视频ID
									var tempVideoId = data.share.substring(data.share.lastIndexOf("/") + 1, data.share.length);
									pingBgUrl(data.pic, tempVideoId);
									// checkPPODOver(tempVideoId);
					            } else {
					                // $("#fileurl").val(data.orgfile);
					            }
					            task.resolve();
					            uploader.skipFile(file);
					        } else {
					            task.resolve();
					            //拿到上传文件的唯一名称，用于断点续传
					            uniqueFileName = md5('' + userInfo.userId + file.name + file.type + file.lastModifiedDate + file.size);
					            _cache[file.name] = uniqueFileName;
					            userInfo.uniqueFileName = uniqueFileName;
					        }
					    },
					        function (jqXHR, textStatus, errorThrown) { //任何形式的验证失败，都触发重新上传
					            task.resolve();
					            //拿到上传文件的唯一名称，用于断点续传
					            uniqueFileName = md5('' + userInfo.userId + file.name + file.type + file.lastModifiedDate + file.size);
					            userInfo.uniqueFileName = uniqueFileName;
					        });
					});
					return $.when(task);
				}
            },
           
			beforeSend: function (block) {
                //分片验证是否已传过，用于断点续传
				var tempFileType = block.file.type.toLowerCase();
				if(tempFileType.indexOf('mp4') < 0 && tempFileType.indexOf('webm') < 0 || testTemp == 1) {
					return;
				}else {
					var task = new $.Deferred();
					$.ajax({
					    type: "GET",
					    url: ServerUrl,
					    data: {
					        status: "chunkCheck",
					        name: uniqueFileName,
					        chunkIndex: block.chunk,
					        size: block.end - block.start
					    },
					    cache: false,
					    timeout: 1000,
					    //todo 超时的话，只能认为该分片未上传过
					    dataType: "json"
					}).then(function (data, textStatus, jqXHR) {
					    if (data.ifExist) { //若存在，返回失败给WebUploader，表明该分块不需要上传
					        task.reject();
					    } else {
					        task.resolve();
					    }
					},
					    function (jqXHR, textStatus, errorThrown) { //任何形式的验证失败，都触发重新上传
					        task.resolve();
					    });
					return $.when(task);
				}
            },
            
			afterSendFile: function (file) {
				var tempFileType = file.type.toLowerCase();
				if(tempFileType.indexOf('mp4') < 0 && tempFileType.indexOf('webm') < 0 || testTemp == 1) {
					return;
				}
                var chunksTotal = 0;
                chunksTotal = Math.ceil(file.size / chunkSize)
                if (chunksTotal >= 1) {
                    //合并请求
                    var task = new $.Deferred();
                    $.ajax({
                        type: "GET",
                        url: ServerUrl,
                        data: {
                            status: "chunksMerge",
                            category: userInfo.category ? userInfo.category : "",
                            tmpl: userInfo.tmpl,
                            tmplname: userInfo.tmplname,
                            name: uniqueFileName,
                            chunks: chunksTotal,
                            ext: file.ext,
                            fileoldname: file.name.replace("." + file.ext, ""),
                            md5: md5Mark
                        },
                        cache: false,
                        dataType: "json"
                    }).then(function (data, textStatus, jqXHR) {
                        //todo 检查响应是否正常
                        task.resolve();
                        file.path = data.path;
                        UploadComlate(file);
                        if (data.title) {
                            if (data.share) {
								var tempVideoId = data.share.substring(data.share.lastIndexOf("/") + 1, data.share.length);
								pingBgUrl(data.pic, tempVideoId);
								// checkPPODOver(tempVideoId);
                            } else {
                                // $("#fileurl").val(data.orgfile);
                            }
                        }
                    },
					function (jqXHR, textStatus, errorThrown) {
						task.reject();
					});
                    return $.when(task);
                } else {
                    UploadComlate(file);
                }
            }
        });
    //#############################################
    var $ = jQuery, state = 'pending';
	
    uploader = WebUploader.create({
        dnd: "#chosevideo",
        paste: document.body,
        auto: true,
        resize: false,
        // 不压缩image
        swf: BASE_URL + '/upload/js/Uploader.swf',
        // swf文件路径
        server: ServerUrl,
        // 文件接收服务端。
        pick: {
            id: '#chosevideo',
        },
        accept: {
            title: 'Files'
			// 这里不用设置，安卓手机会有问题
            // extensions: 'mp4',
            // mimeTypes: '.mp4'
        },
        duplicate: true,
        chunked: true,
        chunkSize: chunkSize,
        threads: 1,
        multiple: false, //多文件选择
        formData: function () {
            return $.extend(true, {}, userInfo);
        }
    });
    
	// 当有文件添加进来的时候
    uploader.on('fileQueued',
        function (file) {
			var tempFileType = file.source.type.toLowerCase();
			if (tempFileType.indexOf('mp4') < 0 && tempFileType.indexOf('webm') < 0 || testTemp == 1) {
				showDalogleInfo({'text': '请选择选择mp4、webm格式的视频上传', 'time': 2000});
				return;
			} else {
				$('#showToast').html('<div id="jindu"></div><div id="jinduwb">请稍后...</div>');
				var file_size_M = roundNumber(((file.size / 1024) / 1024), 1);	
			}
        });
    
	// 文件上传过程中创建进度条实时显示。
    uploader.on('uploadProgress',
        function (file, percentage) {
			$('#jinduwb').html('上传中' + parseInt(percentage * 100) + '%...');
			$('#jinduwb').css({'z-index': '100'});
			$('#jindu').css({'width': parseInt(percentage * 100) + '%','z-index': '99'});
			if (parseInt(percentage * 100) == 100) {
				$('#jinduwb').html('上传完成100%');
				$('#jindu').css({'width': '100%' ,'z-index': '2'});	
				$('#jinduwb').css({'z-index': '3'});
			}
        });
    
	//文件上传错误
    uploader.on('uploadError',
        function (file, reason) {
            if (state != 'stoped' && state != 'finished') {
                //jError("上传错误，可能是网络原因，请稍后重试",{HorizontalPosition : 'center',VerticalPosition:'center'});
                if (reason)
					showDalogleInfo({text: reason, time: 2000});
                else
					showDalogleInfo({text: '上传错误，可能是网络原因，请稍后重试', time: 2000});
            }
        });
   
	//文件上传成功
    uploader.on('uploadSuccess',
        function (file) {
            // console.log("上传完成的信息", file);
        });
    
	uploader.on('uploadComplete',
        function (file) {
            // console.log("Complete！" + file.id);
        });
    
	uploader.on('all', function (type) {
        if (type === 'startUpload') {
            state = 'started';
            // console.log("开始上传了~");
        } else if (type === 'stopUpload') {
            state = 'stoped';
            // console.log("开始暂停了~");
        } else if (type === 'uploadFinished') {
            state = 'finished';
            // console.log("开始结束了~");
        } else if (type === 'error') {
			 showDalogleInfo({text: '上传失败请重试', time: 1500});
			 setTimeout(function(){
				window.location.reload();
			 }, 1500);
			 
        }
		
    });
});
function UploadComlate(file) {
    console.log("done###" + file.id);
}
function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}
